﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace tab2sql
{
    class FixedDelimiter
    {

        public static string DoConversion(string input)
        {
            string[] Lines = input.Split('\n');
            string theResult = "";

            
            foreach (string Line in Lines)
            {
                Regex r = new Regex(@"[\s]{3,}");
                string Line2 = r.Replace(Line,"#");
                int i = 0;

                //string proposedDelimiter = getDelimiter(Line2, 5);
                string proposedDelimiter = "#";
                string[] fields = Regex.Split(Line2, proposedDelimiter);
                
                foreach (string field in fields)
                {
                    if (field.Trim().Length > 0)
                    {
                        i++;
                        theResult += field;
                        theResult += "|";
                        
                    }
          

                }
                if (i > 0)
                {
                    theResult += "------>" + proposedDelimiter.Length.ToString();
                    theResult += Environment.NewLine;
                    theResult += "------>" + Line2;
                    theResult += Environment.NewLine;
                }

                
                
            }
            return theResult;
        }

        private static string replicate(char C, int x)
        {
            string endResult = "";
            char[] result = new char[x];
            for (int i = 0; i < x; i++)
            {
                endResult += C;
                
            }



            return endResult;
        }

        private static Char Chr(int i)
        {
            //Return the character of the given character value
            return Convert.ToChar(i);
        }


        public static string getDelimiter(string line, int desiredColumns)
        {
            
            string[] dlimiters = new string[9];
            for (int i = 0; i < 9; i++)
            {
                dlimiters[i] = replicate(Chr(35), 9 - i);
            }
           
            string finalDelimiter = "";
            int howManyCols = -1;
            foreach (string delimiter in dlimiters)
            {
                if (howManyCols != desiredColumns)
                {
                    string[] fields = Regex.Split(line, delimiter);

                    howManyCols = fields.Count();
                    if (howManyCols == desiredColumns)
                    {
                        finalDelimiter = delimiter;
                    }
                }
            }

            return finalDelimiter;
        }


    }



}
